import React, { useContext, useEffect, useMemo, useRef, useState } from 'react'
import { Spin, Form, DatePicker, Tooltip, Button, message } from 'antd';
import moment from 'moment';
import classNames from 'classnames';
import { useMount } from 'react-use';

import { SearchInput } from '@/components/UserForm';
import { isSuccess } from '@/utils/request';
import BizIcon from '@/components/BizIcon';
import If from '@/components/If';
import OrganizationSelect from '@/components/OrganizationSelect';
import authHelper from '@/utils/auth/helper';

import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import { feedbackHandleStatus, feedbackProblemTypeEnum, feedbackAssignTypeEnum } from '@/pages/SalaryManage/enum';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import { queryNotHandle, noticeHandled, queryDateRange } from '@/services/salaryManage/salaryConfirm';
import { commonColumn, dateColumn, datetimeColumn } from '@/pages/SalaryManage/utils/TableUtil';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

import useFetchCountInfo from './hooks/useFetchCountInfo';
import useTableWrapper from './hooks/useTableWrapper';
import useTransfer from './hooks/useTransfer';
import useDealWith from './hooks/useDealWith';

const { MonthPicker, RangePicker } = DatePicker;

const SearchWrapper = React.forwardRef(
    ({ form, onSearch, monthRange, model, organizationList }, ref) => {
        const { store: { organizationCode }, mergeTabStore } = useContext(TabStoreContext);
        const { getFieldDecorator } = form;
        ref(form);

        const disabledDate = current => {
            if (current && monthRange?.length) {
                return monthRange.indexOf(current.startOf('month').format('YYYY-MM-DD')) === -1;
            }
            if (!monthRange?.length) {
                return true;
            }
            return !monthRange;
        };

        const onChangeMonth = (date, dateString) => {
            mergeTabStore({
                period: dateString
            });
        };

        const handleOrganizationChange = value => {
            form.setFieldsValue({
                employeeCode: undefined,
                v_salaryDate: undefined,
                period: undefined
            });
            mergeTabStore({
                period: undefined,
                organizationCode: value
            });
        };

        return (
            <div>
                <Search.Wrapper onSearch={onSearch}>
                    <TwoColHead
                        left={
                            <Search.Commonly>
                                <Search.Item label="行政机构">
                                    {getFieldDecorator('organizationCode', {
                                        initialValue: organizationCode
                                    })(
                                        <OrganizationSelect
                                            isStrictly
                                            isNeedPermission
                                            style={{ width: 220 }}
                                            treeDataFromProp
                                            treeDataList={organizationList}
                                            onChange={handleOrganizationChange}
                                            allowClear={false}
                                        />
                                    )}
                                </Search.Item>
                                <Search.Item label="月份">
                                    {getFieldDecorator('v_salaryDate', { initialValue: model?.v_salaryDate })(
                                        <MonthPicker disabledDate={disabledDate} onChange={onChangeMonth} />
                                    )}
                                </Search.Item>
                            </Search.Commonly>
                        }
                        right={
                            <TwoColHead
                                right={
                                    <AutoDivider>
                                        {/* <Tooltip title="自定义表头">
                                        <BizIcon
                                            type="searchbar_modifyheader_icon_default"
                                            className={salaryStyle.iconfont22}
                                        />
                                    </Tooltip> */}
                                    </AutoDivider>
                                }
                                addMarginAtOuter={false}
                                addMarginInRightChild={false}
                                style={{ flex: 1 }}
                            />
                        }
                        addMarginInRightChild={false}
                    />

                    <Search.More>
                        <Search.Item label="提交时间">
                            {getFieldDecorator('v_submitTime')(<RangePicker style={{ width: '220px' }} />)}
                        </Search.Item>
                        <Search.Item label="提交人">
                            <span>
                                {getFieldDecorator('employeeCode')(
                                    <SearchInput
                                        params={{
                                            organizationCode: form?.getFieldValue('organizationCode')
                                        }}
                                        getData={async params => {
                                            if (!params.organizationCode) {
                                                return [];
                                            }
                                            const employeeResponse = await queryEmployeeList({
                                                organizationCode: params.organizationCode
                                            });
                                            return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                        }}
                                        selectProps={{
                                            placeholder: '请输入员工姓名',
                                            allowClear: true
                                        }}
                                        fieldsName={{
                                            value: 'employeeCode',
                                            title: 'name'
                                        }}
                                        style={{ width: '12.875em' }}
                                    />
                                )}
                            </span>
                        </Search.Item>
                    </Search.More>
                </Search.Wrapper>
            </div>
        );
    }
);

const tableColumns = ({ operateConfig }) => [
    {
        title: (
            <EmployeeNameWrapper
                left={
                    <span
                        className={classNames(salaryStyle.circle)}
                        style={{ visibility: 'hidden' }}
                    />
                }
                name="姓名"
            />
        ),
        dataIndex: 'employeeName',
        fixed: 'left',
        width: 146,
        render(text, record) {
            return (
                <EmployeeNameWrapper
                    left={
                        <span
                            className={classNames(salaryStyle.circle)}
                            style={{ visibility: record.receiver ? 'hidden' : 'visible' }}
                        />
                    }
                    name={<span title={text}><EmptyPlaceHolder value={text} /></span>}
                />
            );
        }
    },
    commonColumn({
        title: '工号',
        dataIndex: 'employeeNo',
        fixed: 'left',
        width: 120
    }),
    commonColumn({
        title: '组织机构',
        dataIndex: 'departmentName',
        width: 220
    }),
    dateColumn(
        {
            title: '薪资月份',
            dataIndex: 'salaryDate',
            width: 95
        },
        { pattern: 'YYYY-MM' }
    ),
    datetimeColumn({
        title: '提交时间',
        dataIndex: 'submitTime',
        width: 180
    }),
    commonColumn({
        title: '反馈编号',
        dataIndex: 'feedbackNo',
        width: 120
    }),
    {
        title: '反馈内容',
        dataIndex: 'feedback',
        render(text) {
            return (
                <pre
                    style={{
                        marginBottom: 0,
                        display: 'inline-block',
                        whiteSpace: 'break-spaces',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </pre>
            );
        }
    },
    {
        title: '问题类型',
        dataIndex: 'problemType',
        width: 100,
        render(text) {
            return <EmptyPlaceHolder value={feedbackProblemTypeEnum.getShowName(text)} />;
        }
    },
    commonColumn({
        title: '处理结果',
        dataIndex: 'respondContent',
        width: 200,
        render(text) {
            return (
                <pre
                    style={{
                        marginBottom: 0,
                        display: 'inline-block',
                        whiteSpace: 'break-spaces',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </pre>
            );
        }
    }),
    {
        title: '分配方式',
        dataIndex: 'assignType',
        width: 100,
        render(text) {
            return <EmptyPlaceHolder value={feedbackAssignTypeEnum.getShowName(text)} />;
        }
    },
    {
        title: '原因',
        dataIndex: 'reason',
        width: 120,
        render(text) {
            return (
                <pre
                    style={{
                        marginBottom: 0,
                        display: 'inline-block',
                        whiteSpace: 'break-spaces',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </pre>
            );
        }
    },
    {
        title: '操作',
        dataIndex: 'v_operate',
        fixed: 'right',
        width: 180,
        align: 'center',
        render(text, record) {
            const { /* onIM, */ onShowDealWith, onNoticeHandled, onShowTransfer } = operateConfig;

            return (
                <AutoDivider>
                    {/* TODO open
                    <If condition={authHelper.checkCode('finance:salary:confirm:feedback:im')}>
                        <Tooltip title="IM联系">
                            <Button className={salaryStyle.operateIcon} onClick={() => onIM(record)}>
                                <BizIcon type="listfunction_interview_contact_icon_default" />
                            </Button>
                        </Tooltip>
                    </If>
                    */}

                    <If condition={authHelper.checkCode('finance:salary:confirm:feedback:record')}>
                        <Tooltip title="结果记录">
                            <Button className={salaryStyle.operateIcon} onClick={() => onShowDealWith(record)}>
                                <BizIcon type="tijiaozhaopinxuqiu" />
                            </Button>
                        </Tooltip>
                    </If>

                    <If condition={authHelper.checkCode('finance:salary:confirm:feedback:noticedone')}>
                        <Tooltip title="通知已解决">
                            <Button className={salaryStyle.operateIcon} onClick={() => onNoticeHandled(record)}>
                                <BizIcon type="icontongzhiyijiejue" />
                            </Button>
                        </Tooltip>
                    </If>

                    {/* 存在接收人，但处理状态为未处理时显示为转配 */}
                    <If
                        condition={
                            authHelper.checkCode('finance:salary:confirm:feedback:realot') &&
                            record.receiver &&
                            record.status === feedbackHandleStatus.HANDLING
                        }
                    >
                        <Tooltip title="转配">
                            <Button className={salaryStyle.operateIcon} onClick={() => onShowTransfer(record)}>
                                <BizIcon type="zhidingfuzeren1" />
                            </Button>
                        </Tooltip>
                    </If>
                </AutoDivider>
            );
        }
    }
];

const Handle = () => {
    const { store: { organizationCode, period }, mergeTabStore } = useContext(TabStoreContext);

    const [pageLoading, setPageLoading] = useState(false);
    const { pagination, setDataSource, setPagination, render: TableWrapper } = useTableWrapper();

    // 当前操作行数据
    const [operateRecord, setOperateRecord] = useState(null);
    const [monthRange, setMonthRange] = useState([]);
    const [organizationTreeData, setOrganizationTreeData] = useState({});
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);
    // 获取页签统计个数
    const fetchCountInfo = useFetchCountInfo();
    const searchForm = useRef();

    const getSearchCondition = () => searchForm.current?.getFieldsValue();
    // 获取查询条件
    const getPostData = searchCondition => {
        const { v_salaryDate, v_submitTime, ...postData } = searchCondition;

        if (v_salaryDate) {
            postData.salaryDate = v_salaryDate?.startOf('month')?.format('YYYY-MM-DD');
        }

        if (v_submitTime && v_submitTime.length > 0) {
            postData.submitStartTime = v_submitTime[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
            postData.submitEndTime = v_submitTime[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }

        return {
            ...postData,
            pageNo: postData?.current || pagination.current || 1,
            pageSize: postData?.pageSize || pagination.pageSize || 10
        };
    };

    const search = searchCondition => {
        const preCondition = (!searchCondition || (searchCondition?.current || searchCondition?.pageSize))
            ? { organizationCode: selectOrganizationCode, ...getSearchCondition(), ...searchCondition || {} }
            : searchCondition;
        const postData = getPostData(preCondition);

        if (!organizationCode && postData.organizationCode) {
            mergeTabStore({
                organizationCode: postData.organizationCode
            });
        }
        setPageLoading(true);
        queryNotHandle(postData)
            .then(searchResponse => {
                if (isSuccess(searchResponse)) {
                    const { pageSize, total, pageNo: current, rows } = searchResponse.data;
                    setDataSource(rows);
                    setPagination({
                        ...pagination,
                        pageSize: pageSize || 10,
                        current: current || 1,
                        total
                    });
                    fetchCountInfo({ organizationCode: postData.organizationCode });
                } else {
                    message.error(searchResponse.msg);
                }
            })
            .finally(() => setPageLoading(false));
    };

    const { onShowDealWith, render: renderDealWithModal } = useDealWith(operateRecord, setOperateRecord, search);

    const { onShowTransfer, render: renderTransferModal } = useTransfer(
        organizationCode,
        operateRecord,
        setOperateRecord,
        search
    );

    const EnhancedSearchWrapper = useMemo(
        () =>
            Form.create({
                /* 不立即搜索
                onValuesChange: (props, changedValues, allValues) => {
                    search(allValues);
                }
                */
            })(SearchWrapper),
        []
    );

    const onIM = record => {
        console.log('record', record);
    };

    const onNoticeHandled = record => {
        setPageLoading(true);
        noticeHandled({ id: record.id })
            .then(response => {
                if (!isSuccess(response)) {
                    message.error(response.msg);
                    return;
                }
                message.success('通知员工成功！');
                search();
            })
            .finally(() => setPageLoading(false));
    };

    useEffect(() => {
        const requestOrganizationCode = selectOrganizationCode;

        if (requestOrganizationCode) {
            queryDateRange({ organizationCode: requestOrganizationCode }).then(response => {
                if (isSuccess(response)) {
                    const range = response.data;
                    setMonthRange(range && range.length > 0 ? range : []);
                } else {
                    message.error(response.msg);
                }
            });
        }
    }, [selectOrganizationCode]);

    useEffect(() => {
        setSelectOrganizationCode(organizationCode);
    }, [organizationCode]);

    useMount(() => {
        fetchOrganizationListAndDefault(organizationCode)
            .then(({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);

                const condition = getPostData({
                    ...getSearchCondition(),
                    organizationCode: defaultSelectCode,
                    v_salaryDate: period ? moment(period, 'YYYY-MM-DD') : null
                });
                if (defaultSelectCode) {
                    search(condition);
                }
            });
    });

    const salaryDate = period ? moment(period, 'YYYY-MM-DD') : null;

    return (
        <Spin spinning={pageLoading}>
            <EnhancedSearchWrapper
                monthRange={monthRange}
                onSearch={search}
                wrappedComponentRef={form => {
                    searchForm.current = form;
                }}
                model={{
                    v_salaryDate: salaryDate
                }}
                organizationCode={selectOrganizationCode}
                organizationList={organizationTreeData}
            />
            <TableWrapper
                columns={tableColumns({
                    operateConfig: {
                        onIM,
                        onNoticeHandled,
                        onShowDealWith,
                        onShowTransfer
                    }
                })}
                search={search}
            />

            {renderDealWithModal()}
            {renderTransferModal()}
        </Spin>
    );
};

export default React.memo(Handle);
